import sys
import socket
import struct

from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi

from fun_about import AboutUI
from mainUI import Ui_MainWindow

data_dict = {}


class SocketRecv(QThread):
    def __init__(self, IP, port, action):
        super().__init__()
        self.IP = IP
        self.port = port
        self.action = action

    def run(self):
        try:
            while True:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((self.IP, self.port))
                buf = s.recv(1024)
                intData = struct.unpack('l', buf[0:8])[0]
                floatData = struct.unpack('d', buf[8:16])[0]
                data_dict[intData][2] = True
                data_dict[intData][3] = floatData
                self.action()
                print(intData, floatData)
        except socket.error as msg:
            print(msg)
            self.terminate()


class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, pic_dict, ip):
        global data_dict
        super(MainUI, self).__init__()
        loadUi('mainUI.ui', self)
        data_dict = pic_dict
        self.aboutWindow = AboutUI()
        self.aboutWindow.setFixedSize(460, 397)
        self.total = len(data_dict)
        self.inflateList()
        self.setWindowTitle(ip)
        self.pushButton.clicked.connect(self.openAbout)
        self.pushButton_2.clicked.connect(self.resetStatus)
        self.pushButton_3.clicked.connect(self.startThread)
        self.socketThread = SocketRecv(ip, 8000, self.inflateList)
        self.startThread()

    def openAbout(self):
        self.aboutWindow.show()

    def resetStatus(self):
        for key in data_dict:
            data_dict[key][2] = False
        self.inflateList()

    def inflateList(self):
        self.listWidget.clear()
        signedin = 0
        for key in data_dict:
            item = QtWidgets.QListWidgetItem()
            s = ''
            if data_dict[key][2]:
                s = '——已签到，识别准确率：' + str(data_dict[key][3])
                signedin = signedin + 1
            item.setText(data_dict[key][1] + s)
            self.listWidget.addItem(item)
        self.label.setText('当前签到：' + str(signedin) + '/' + str(self.total))

    def startThread(self):
        if not self.socketThread.isRunning():
            self.socketThread.start()
